using newsApi.Services;
using newsApi.Models;
using Microsoft.AspNetCore.Mvc;

namespace newsApi.Controllers;
[ApiController]
  // [Route("/")]
  [Route("api/[controller]")]
public class ChanelController:ControllerBase
{
    private readonly ChanelsService _chanelsService;
    public ChanelController(ChanelsService chanelsService) =>
    _chanelsService=chanelsService;


    [HttpGet]

     public async Task<List<Chanel>> Get() =>
        await _chanelsService.GetAsync();

    // public async Task<IActionResult> Get(){
    //   List<string> result=new List<string>();
    //   var chanels=await _chanelsService.GetAsync();
    //   foreach(var c in chanels)
    //   {
    //     result.Add(c.Title);
    //   }
    //   return Ok(result);
    // }
    
    [HttpGet("{id:length(24)}")]
    public async Task<ActionResult<Chanel>> Get(string id )
    {
        var chanel = await _chanelsService.GetAsync(id);
        if (chanel is null)
        {
            return NotFound();
        }
        return chanel;
    }

  [HttpPost]
    public async Task<IActionResult> Post(Chanel newChanel)
    {
        await _chanelsService.CreateChanel(newChanel);
        return CreatedAtAction(nameof(Get), new { id = newChanel.Id }, newChanel);;
    }


 [HttpPut("{id:length(24)}")]

     public async Task<IActionResult> Update(string id, Chanel updatedChanel)
     {
         var chanel = await _chanelsService.GetAsync(id);
         if (chanel is null)
         {
             return NotFound();
         }
         updatedChanel.Id = chanel.Id;
         await _chanelsService.UpdateChanel(id,updatedChanel);
         return NoContent();
     }

     [HttpDelete("{id:length(24)}")]
     public async Task<IActionResult> Delete(string id)
     {
         var chanel = await _chanelsService.GetAsync(id);
         if (chanel is null)
         {
             return  NotFound();
         } 
         await _chanelsService.RemoveChanel(id);
         return NoContent();   
     }


    }